﻿using eBay.Service.Core.Sdk;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using eBay.Service.Core.Soap;
using eBay.Service.Util;

namespace eBayAPICall
{
    public class ApiContextHelper
    {
        private Dictionary<ApiContextConfigEntity, ApiContext> dicContexts = new Dictionary<ApiContextConfigEntity, ApiContext>();

        private static ApiContextHelper instance = null;
        private static object lockObj = new object();
        private ApiContextHelper() 
        {
            dicContexts = new Dictionary<ApiContextConfigEntity, ApiContext>();
        }

        public static ApiContextHelper GetInstance()
        {
            if (instance == null)
            {
                lock (lockObj)
                {
                    if (instance == null)
                    {
                        instance = new ApiContextHelper();
                    }
                }
            }

            return instance;
        }

        public ApiContext GetContext(ApiContextConfigEntity config)
        {
            if (config == null)
                throw new ArgumentNullException("config");

            if (!this.dicContexts.ContainsKey(config))
            {
                ApiContext context = new ApiContext();
                context.SoapApiServerUrl = config.SoapApiServerUrl;

                ApiCredential credential = new ApiCredential();
                credential.eBayToken = config.eBayToken;
                context.ApiCredential = credential;
                context.Site = config.SiteCode;

                ApiLogManager logger = new ApiLogManager();
                logger.EnableLogging = config.EnableLog;
                if (config.EnableFileLog)
                    logger.ApiLoggerList.Add(new FileLogger(config.LogFileName,config.LogInfomations,config.LogApiMessagees, config.LogExceptions));

                if (config.EnableConsoleLog)
                    logger.ApiLoggerList.Add(new ConsoleLogger(config.LogInfomations, config.LogApiMessagees, config.LogExceptions));

                context.ApiLogManager = logger;
                dicContexts.Add(config, context);
            }

            return this.dicContexts[config];
        }
    }
}
